/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */
package au.com.lastweekend.openjaws.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Thread that loops until stopped, executing some process and then sleeping for a certain period.
 * 
 * @author ggardner
 * 
 */
public abstract class LoopSleepThread extends Thread {

    private Logger logger = LoggerFactory.getLogger(LoopSleepThread.class);
    private int minSleep = 1;
    private int maxSleep = 5 * 60;
    private volatile boolean stopped = false;
    private volatile boolean sleeping = false;
    private Object stopLock = new Object();

    public LoopSleepThread(Logger logger) {

        super();
        this.logger = logger;
    }

    public LoopSleepThread(String name, Logger logger) {

        super(name);
        this.logger = logger;

    }

    public LoopSleepThread(ThreadGroup group, String name, Logger logger) {

        super(group, name);
        this.logger = logger;

    }

    /**
     * Run before the first iteration of the main loop
     */
    protected void beforeLoop() {

        // do nothing;
    }

    /**
     * Called each iteration of the loop
     */
    protected abstract void inLoop();

    /**
     * 
     * TODO: Make this milliseconds for the general case.
     * 
     * @return Seconds to delay
     */
    protected int delay() {

        return getMaxSleep();
    }

    /**
     * Called in a finally block when the loop has finished
     */
    protected void stopped() {

        // do nothing;
    }

    @Override
    public final void run() {

        try {
            beforeLoop();

            while (!stopped) {
                inLoop();

                sleep();
            }
        } catch (Exception e) {
            logger.error("Stopping due to exception",e);
        
        } finally {
            stopped();
            logger.info("Stopped");
        }
    }

    private void sleep() {

        int delay = delay();
        int sleepTime = Math.max(Math.min(delay, maxSleep), minSleep);

        if (delay != sleepTime) {
            logger.warn(String.format("Delay %ds, outside range %ds to %ds", delay, minSleep, maxSleep));
        }

        synchronized (stopLock) {
            sleeping = !stopped;
        }

        if (sleeping) {
            try {
                logger.info(String.format("Sleeping for %ds", sleepTime));
                sleep(sleepTime * 1000);
            } catch (InterruptedException e) {
                if (!stopped) {
                    logger.warn("Interrupted while sleeping for next reading", e);
                }
            } finally {
                sleeping = false;
            }
        }

    }

    /**
     * Stops the daemon loop.
     * 
     * If we are currently sleeping we interrupt immediately, otherwise we'll wait for the loop iteration to finish
     * 
     */
    public final void shutdown() {

        synchronized (stopLock) {
            if (isAlive()) {
                logger.debug("Stopping...");

                this.stopped = true;
                if (this.sleeping) {
                    logger.debug("Interrupting sleep");
                    this.interrupt();
                }
            }
        }
        try {
            this.join();
        } catch (InterruptedException e) {
            logger.error("Interrupted while stopping", e);
        }

    }

    /**
     * 
     * @return the minimum sleep period between readings in seconds
     */
    public int getMinSleep() {

        return minSleep;
    }

    /**
     * @param minSleep
     *            the minimum period between readings in seconds - default 1 second
     */
    public void setMinSleep(int minSleep) {

        this.minSleep = minSleep;
    }

    /**
     * @return the maximum sleep period between readings in seconds
     */
    public int getMaxSleep() {

        return maxSleep;
    }

    /**
     * @param maxSleep
     *            the maximum sleep period between readings in seconds - default 5 minutes
     */
    public void setMaxSleep(int maxSleep) {

        this.maxSleep = maxSleep;
    }

}